package main.com.yyx.pool;


import java.sql.SQLException;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static main.com.yyx.pool.MyPooledConnection.NOTBUSYCOUNTMAX;

/**
 * 连接池大管家，负责连接池的生命周期，并且提供一系列生命周期需要的生态环境：
 * 1. 定时检测任务AdminTaskTimer
 * 2. 全局的线程池
 */
public class PooledConnectionPoolManager {

    //MyDefaultPool持有一个管道集合，基于多线程的考虑，这里使用了Vector。
    private static Vector<MyPooledConnection> myPooledConnectionVector = new Vector<>();

    public static Vector<MyPooledConnection> getMyPooledConnectionVector() {
        return myPooledConnectionVector;
    }

    public PooledConnectionPoolManager() {
        init();
    }

    private void init() {
        ScheduledExecutorService executorService= Executors.newScheduledThreadPool(1);
        DaemonThread daemonThread=new DaemonThread();
        while (true){
            executorService.schedule(daemonThread,60, TimeUnit.SECONDS);
        }
    }

    class DaemonThread extends Thread{

        @Override
        public void run() {
            for (MyPooledConnection myPooledConnection:
                 myPooledConnectionVector) {

                if(!myPooledConnection.isBusy()){
                    //不忙就尝试关闭
                    if(myPooledConnection.getNotbusyCount()==NOTBUSYCOUNTMAX){
                        try {
                            myPooledConnection.getConnection().close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                            //事务保证，but 性能低，效率低
                            break;
                        }
                        //
                        myPooledConnectionVector.removeElement(myPooledConnection);
                    }else {
                        //
                        myPooledConnection.increNotbusyCount();
                    }
                }else {
                    myPooledConnection.clearNotbusyCount();
                }
            }
        }
    }
}
